package com.classtest.DemoExpend.controller;

import com.alibaba.fastjson.JSON;
import com.classtest.DemoExpend.bean.DbUser;
import com.classtest.DemoExpend.dao.DbUserDao;
import com.classtest.DemoExpend.service.DbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@RestController
public class LoginController {

    @Autowired
    DbUserService dbUserService;

    @RequestMapping("/login")
    public String login(@RequestBody String json, HttpServletRequest request){
        String flag = "error";
        HashMap<String, Object> res = new HashMap<>();
        try{
            if(dbUserService.getUserByMessage(json).isEmpty()){
                res.put("error","账号密码错误");
            }else {
                List<DbUser> userByMessage = dbUserService.getUserByMessage(json);
                DbUser dbUser = userByMessage.get(0);
                request.getSession().setAttribute("user",dbUser);
                if (dbUser.getType().equals("普通卖家")){
                    flag = "ok";
                }
            }
        }catch (Exception e){
            res.put("error",e.toString());
        }

        res.put("flag",flag);
        return JSON.toJSONString(res);
    }

}
